<template>
    <div class="order-detail-box">
        <van-nav-bar title="订单详情" left-text="返回" left-arrow @click-left="close">
            <template #right>
                <van-icon name="fire-o" color="#ee0a24" size="20"/>
            </template>
        </van-nav-bar>
        <br>
        <van-steps :active="active" v-if="detail.status === 5 && active !== 3">
            <van-step>买家申请退货</van-step>
            <van-step>商家同意申请</van-step>
            <van-step>退货成功</van-step>
        </van-steps>

        <div class="order-status">
            <div class="status-item">
                <label>订单状态：</label>
                <span>{{ detail.status | filterStatus}}</span>
            </div>
            <div class="status-item">
                <label>订单编号：</label>
                <span>{{ detail.orderSn }}</span>
            </div>
            <div class="status-item">
                <label>下单时间：</label>
                <span>{{ detail.createTime | formatDate}}</span>
            </div>
            <div class="status-item" v-if="detail.paymentTime">
                <label>支付时间：</label>
                <span>{{ detail.paymentTime | formatDate}}</span>
            </div>
            <div class="status-item">
                <label>配送方式：</label>
                <span>普通快递</span>
            </div>
            <div class="status-item">
                <label>收货信息：</label>
                <span>{{detail.receiverName}} {{detail.receiverPhone}}
                    {{detail.receiverProvince}} {{detail.receiverCity}} {{detail.receiverRegion}} {{detail.receiverDetailAddress}}</span>
            </div>
            <div v-if="detail.deliveryTime">
                <br>
                <br>
                <van-divider>物流信息</van-divider>
                <div class="price-item" v-if="detail.deliverySn">
                    <label>快递单号：</label>
                    <span>{{detail.deliverySn}}</span>
                    <br>
                    <label>快递公司：</label>
                    <span>{{detail.deliveryCompany}}</span>
                    <br>
                    <label>发货日期：</label>
                    <span>{{detail.deliveryTime | formatDate}}</span>
                </div>
            </div>
            <br>
            <br>
            <van-divider>商品信息</van-divider>
            <van-card
                    v-for="item in detail.orderItemList"
                    :key="item.id"
                    style="background: #fff"
                    :num="item.productQuantity"
                    :price="item.productPrice"
                    desc="全场包邮"
                    :title="item.productName"
                    :thumb="prefix(item.productPic)"
                    @click="toDetail(item.productId)"
            />
            <van-button v-if="detail.status == 0" style="margin-bottom: 10px" color="#1baeae" block @click="showPayFn">
                去支付
            </van-button>
            <van-button type="warning" v-if="detail.status === 0" block
                        @click="cancelOrder(orderId)">取消订单
            </van-button>
            <van-button type="primary" v-if="detail.status === 2" block
                        @click="confirmOrder(orderId)">确认收货
            </van-button>
            <br>
            <van-button type="warning" v-if="detail.status === 2" block
                        @click="returnOrder(orderId)">申请退货
            </van-button>
            <van-button type="warning" v-if="detail.status === 3" block
            >评价
            </van-button>
            <van-button
                    type="primary" v-if="detail.status === 5" block
            >商品寄回
            </van-button>
        </div>
        <br>
        <!-- 支付弹窗-->
        <van-popup
                v-model="showPay"
                position="bottom"
                :style="{ height: '24%' }"
        >
            <div :style="{ width: '90%', margin: '0 auto', padding: '20px 0' }">
                <van-button :style="{ marginBottom: '10px' }" color="#1989fa" block @click="payOrder(detail, 1)">支付宝支付
                </van-button>
                <van-button color="#4fc08d" block @click="payOrder(detail, 2)">微信支付</van-button>
            </div>
        </van-popup>

        <!-- 退货弹窗-->
        <van-popup
                v-model:show="showReturn"
                round
                closeable
                position="bottom"
                :style="{ height: '65%' }"
        >
            <div :style="{ width: '90%', margin: '0 auto', padding: '20px 0', textAlign: 'center', fontSize: '18px'}">
                <span :style="{color: 'red'}">申请退货</span>
                <!--                <van-form @submit="onSubmit">-->
                <van-form>
                    <van-field #input>
                        <van-card
                                v-for="item in detail.orderItemList"
                                :key="item.id"
                                style="background: #fff"
                                :num="item.productQuantity"
                                :price="item.productPrice"
                                desc="全场包邮"
                                :title="item.productName"
                                :thumb="prefix(item.productPic)"
                        />
                    </van-field>
                    <van-field name="reason">
                        <template #input>
                            <van-cell
                                    is-link
                                    title="退货原因"
                                    :value="applyParam.reason"
                                    @click="show = true, shettShow = true"/>
                            <van-action-sheet
                                    title="退货原因"
                                    :style="{height: '40%'}"
                                    v-model="shettShow"
                                    :actions="reasonList"
                                    cancel-text="取消"
                                    close-on-click-action
                                    @select="onSelect"
                                    lazy-render
                            />
                        </template>
                    </van-field>
                    <van-field #input>
                        <van-cell title="退款金额*" :value="total"/>
                    </van-field>
                    <van-field
                            #input
                    >
                        <van-field
                                v-model="applyParam.description"
                                rows="1"
                                autosize
                                label="补充描述"
                                type="textarea"
                                placeholder="补充描述，有助于商家更好的处理售后问题"/>
                    </van-field>
                    <van-field #input>
                        <van-button color="#4fc08d" block @click="sendApply">提交</van-button>
                    </van-field>
                </van-form>
            </div>
        </van-popup>
    </div>
</template>

<script>
    import sHeader from '../../../components/SimpleHeader'
    import {getOrderDetail, cancelOrder, confirmOrder, payOrder} from '../../../api/order'
    import {listReason, sendApply, applyStatus} from '../../../api/return'
    import {Dialog, Toast} from 'vant'
    import axios from 'axios';
    import {payOrderAlipay} from "../../../api/pay";
    import baseURL from "../../../utils/baseURLConfig";

    export default {
        name: "orderDetail",
        components: {
            sHeader
        },
        data() {
            return {
                active: 0,
                detail: {},
                showPay: false,
                showReturn: false,
                orderId: -1,
                reasonList: [],
                reasonValue: -1,
                reasonName: '',
                shettShow: false,
                applyParam: {
                    "description": "",
                    "memberUsername": "",
                    "orderId": 0,
                    "orderSn": "",
                    "productBrand": "",
                    "productCount": 0,
                    "productId": 0,
                    "productName": "",
                    "productPic": "",
                    "productPrice": 0,
                    "productRealPrice": 0,
                    "reason": "",
                    "returnAmount": 0,
                    "returnName": "",
                    "returnPhone": ""
                }
            }
        },
        mounted() {
            this.init()
        },
        methods: {
            async init() {
                Toast.loading({
                    message: '加载中...',
                    forbidClick: true
                });
                const {id} = this.$route.query
                this.orderId = id;
                getOrderDetail(id).then(res => {
                    this.detail = res.data
                    console.log(this.detail);
                    this.applyParam.memberUsername = this.detail.memberUsername;
                    this.applyParam.orderId = this.detail.id;
                    this.applyParam.orderSn = this.detail.orderSn;
                    this.applyParam.productBrand = this.detail.orderItemList[0].productBrand;
                    this.applyParam.productCount = this.detail.orderItemList[0].productQuantity;
                    this.applyParam.productId = this.detail.orderItemList[0].id;
                    this.applyParam.productName = this.detail.orderItemList[0].productName;
                    this.applyParam.productPic = this.detail.orderItemList[0].productPic;
                    this.applyParam.productPrice = this.detail.orderItemList[0].productPrice;
                    this.applyParam.productRealPrice = this.detail.orderItemList[0].realAmount;
                    this.applyParam.returnName = this.detail.receiverName
                    this.applyParam.returnPhone = this.detail.receiverPhone
                    Toast.clear()
                    if (this.detail.status === 5) {
                        applyStatus(id).then(res => {
                            this.active = res.data;
                        })
                    }
                })


            },
            cancelOrder(id) {
                Dialog.confirm({
                    title: '确认取消订单？',
                }).then(() => {
                    cancelOrder(id).then(res => {
                        Toast('删除成功')
                        this.init()

                    })
                }).catch(() => {
                    this.init()
                });
            },
            //确认收货
            confirmOrder(id) {
                Dialog.confirm({
                    title: '是否确认订单？',
                }).then(() => {
                    confirmOrder(id).then(res => {
                        if (res.data === 1) {
                            Toast('确认成功')
                            this.init()
                        }
                    })
                }).catch(() => {
                    // on cancel
                });
            },
            //退货申请
            returnOrder(id) {
                this.showReturn = true;
                listReason().then(res => {
                    res.data.map(item => {
                        const data = {
                            name: item.name,
                            id: item.id
                        }
                        this.reasonList.push(data);
                    })
                })
            },
            onSelect(item) {
                this.reasonValue = item.id;
                this.applyParam.reason = item.name;
                // Toast(item.name);
                console.log(this.applyParam)
            },
            //提交申请
            sendApply() {
                sendApply(this.applyParam).then(res => {
                    console.log(res)
                    if (res.data === 1) {
                        this.showReturn = false;
                        Toast.success('提交申请成功')
                        window.location.reload();
                    }
                })
            },
            showPayFn() {
                this.showPay = true
            },
            async payOrder(detail, type) {
                // Toast.loading
                const data = {
                    tradeNo: detail.id,
                    money: detail.totalAmount,
                    subject: 'AvaMall收款方'
                }
                // payOrderAlipay(detail.totalAmount, detail.id).then(res => {
                //     console.log(res.msg)
                //     const divForm = document.getElementsByTagName('divform')
                //     if (divForm.length) {
                //         document.body.removeChild(divForm[0])
                //     }
                //     const div = document.createElement('divform')
                //     div.innerHTML = res.msg // data就是接口返回的form 表单字符串
                //     document.body.appendChild(div)
                //     document.forms[0].setAttribute('target', '_blank') // 新开窗口跳转
                //     document.forms[0].submit()
                //     this.showPay = false
                //     this.init()
                // })
                axios.post(baseURL + '/alipay/pay?money=' + detail.totalAmount + '&subject=AvaMall收款中心&tradeNo=' + detail.id)
                    .then(res => {
                        const divForm = document.getElementsByTagName('divform')
                        if (divForm.length) {
                            document.body.removeChild(divForm[0])
                        }
                        const div = document.createElement('divform')
                        div.innerHTML = res.data.msg // data就是接口返回的form 表单字符串
                        document.body.appendChild(div)
                        document.forms[0].setAttribute('target', '_blank') // 新开窗口跳转
                        document.forms[0].submit()

                        this.showPay = false
                        this.init()
                    })
            },
            close() {
                this.$router.go(-1)
            },
            toDetail(id) {
                this.$router.push({path: `product/${id}`})
            }
        },
        filters: {
            //订单状态：0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭；5->无效订单
            filterStatus(value) {
                if (value === 0) {
                    return '待付款';
                } else if (value === 1) {
                    return '待发货';
                } else if (value === 2) {
                    return '已发货';
                } else if (value === 3) {
                    return '已完成';
                } else if (value === 4) {
                    return '已关闭';
                } else if (value === 5) {
                    return '退货中';
                }
            }
        },
        computed: {
            total() {
                var result = 0;
                this.detail.orderItemList.map(item => {
                    result += item.productPrice;
                })
                this.applyParam.returnAmount = result;
                return '￥' + result;
            }
        }
    }
</script>

<style lang="less" scoped>
    .order-detail-box {
        background: #f7f7f7;

        .order-status {
            background: #fff;
            margin-top: 30px;
            padding: 20px;
            font-size: 15px;

            .status-item {
                margin-bottom: 10px;

                label {
                    color: #999;
                }

                span {

                }
            }
        }

        .order-price {
            background: #fff;
            margin: 20px 0;
            padding: 20px;
            font-size: 15px;

            .price-item {
                margin-bottom: 10px;

                label {
                    color: #999;
                }

                span {

                }
            }
        }

        .van-card {
            margin-top: 0;
        }

        .van-card__content {
            display: flex;
            flex-direction: column;
            justify-content: center;
        }
    }
</style>
